package gat.dto.req.dic;

import com.bitsun.core.common.exception.AppException;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import net.sf.cglib.core.Local;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：liucaihong
 * @date：2024/3/25 10:33
 * @description:
 */
@Data
public class PromoActivityConfigReqDto {

    @ApiModelProperty("是否开启 on 开启 off 关闭")
    private String isOpen;
    @ApiModelProperty("商品数量")
    private Integer goodsNum;
    @ApiModelProperty("用户限购数量")
    private Integer userLimitNum;

    @ApiModelProperty("开始时间")
    private String startTime;

    @ApiModelProperty("结束时间")
    private String endTime;

    @ApiModelProperty("时间区间")
    private List<SeckillTimeData> seckillTime;

    @Data
    public static class SeckillTimeData{

        private String startTime;

        private String endTime;
    }

    public static void hasOverlap(List<SeckillTimeData> seckillTime) {
        List<TimeRange> timeRanges = new ArrayList<>();
        for (SeckillTimeData timeData : seckillTime) {
            timeRanges.add(new TimeRange(LocalTime.parse(timeData.getStartTime()),LocalTime.parse(timeData.getEndTime())));
        }
        validateTimeRanges(timeRanges);
    }

    static void validateTimeRanges(List<TimeRange> timeRanges){
        TimeRange previousRange = null;
        for (TimeRange currentRange : timeRanges) {
            if (!currentRange.overlaps(previousRange)) {
                throw new AppException("时间设置有误");
            }
            previousRange = currentRange;
        }
    }

    static class TimeRange {
        private LocalTime startTime;
        private LocalTime endTime;

        public TimeRange(LocalTime startTime, LocalTime endTime) {
            this.startTime = startTime;
            this.endTime = endTime;
        }

        public boolean overlaps(TimeRange other) {
            return this.startTime.isBefore(this.endTime) && (other == null || other.endTime.isBefore(this.startTime));

        }

        @Override
        public String toString() {
            return startTime + " - " + endTime;
        }
    }



    public static String getCurrentTime(LocalDateTime now, List<SeckillTimeData> seckillTimes){
        String time = now.format(DateTimeFormatter.ofPattern("HH:mm"));
        for (PromoActivityConfigReqDto.SeckillTimeData timeData : seckillTimes) {
            if (timeData.getStartTime().compareTo(time) <= 0 && timeData.getEndTime().compareTo(time) >= 0){
                return timeData.getStartTime() + "-" + timeData.getEndTime();
            }
        }
        return null;
    }

}
